package com.lujianfei.powersearch.widget

import android.content.Context
import android.content.Intent
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.HorizontalScrollView
import android.widget.LinearLayout
import com.lujianfei.powersearch.R
import com.lujianfei.powersearch.database.SearchItemModel
import com.lujianfei.powersearch.ui.subitem.ActivityStackManager.Companion.instance
import com.lujianfei.powersearch.ui.subitem.SubItemActivity
import com.orm.SugarRecord
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.util.*

class BreadCrumbs @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    private var container: LinearLayout? = null
    var parentId: Long = 0
    set(value) {
        field = value
        syncData()
    }


    init {
        LayoutInflater.from(context).inflate(R.layout.widget_breadcrumbs, this, true)
        container = findViewById(R.id.container)
    }

    private fun syncData() {
        runBlocking {
            val searchItemModels = withContext(Dispatchers.IO) {
                val result: MutableList<SearchItemModel> = ArrayList()
                var lastSearchItemModel: SearchItemModel?
                var tmpParentId = parentId
                do {
                    lastSearchItemModel = SugarRecord.findById(SearchItemModel::class.java, tmpParentId)
                    if (null != lastSearchItemModel) {
                        tmpParentId = lastSearchItemModel.parentId
                        result.add(lastSearchItemModel)
                    }
                } while (null != lastSearchItemModel)
                result
            }

            for (i in searchItemModels.indices.reversed()) {
                val d = searchItemModels[i]
                val breadCrumbsItem = BreadCrumbsItem(context)
                breadCrumbsItem.setTextInfo(d.name)
                breadCrumbsItem.setOnClickListener { jumpSubItemActivity(d) }
                if (i == 0) {
                    breadCrumbsItem.hideArrow()
                } else {
                    breadCrumbsItem.showArrow()
                }
                container?.addView(breadCrumbsItem)
            }
            val scrollView = container?.parent as HorizontalScrollView
            scrollView.post { scrollView.fullScroll(FOCUS_RIGHT) }
        }
    }

    fun jumpSubItemActivity(item: SearchItemModel) {
        if (parentId == item.id) {
            return
        }
        if (!instance.popAndFinishToId(item.id)) {
            val intent = Intent(container?.context, SubItemActivity::class.java)
            intent.putExtra("data", item)
            container?.context?.startActivity(intent)
        }
    }
}